package com.atguigu.ucenter.controller;

import com.atguigu.jwtUtils.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenter.entity.Member;
import com.atguigu.ucenter.service.MemberService;
import com.atguigu.ucenter.utils.ConstantPropertiesUtil;
import com.atguigu.ucenter.utils.HttpClientUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    //微信验证码的有效时间，防止csrf攻击
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MemberService memberService;

    //生成微信扫描二维码
    @GetMapping("login")
    public String getWeiXinCode() {
        //请求微信地址
        // 微信开放平台授权baseUrl
        //固定路径%s传参
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //state:使用随机数，存入redis，防止攻击
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("wechar-open-state",state,30, TimeUnit.MINUTES);

        //在路径中填充参数
        String url = String.format(baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                state
        );

        return "redirect:" + url;
    }


    @GetMapping("callback")
    public String getWeiXin(String code, String state) {

        //通过state验证
        String redisState = redisTemplate.opsForValue().get("wechar-open-state");
        System.out.println("redisState:"+redisState);
        if(StringUtils.isEmpty(redisState)||!redisState.equals(state)){
            throw new GuliException(20001,"二维码请求超时,请重新操作");
        }

        try {
            //获取扫码人的信息
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //获取两个值
            String acessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code
            );
            //请求地址，得到返回的信息
            String acessTokenInfo = HttpClientUtils.get(acessTokenUrl);
//            System.out.println(acessTokenInfo);
            //获取信息acesstoken,oppenid
            //字符串转换成map集合
            Gson gson = new Gson();
            HashMap acessTokenMap = gson.fromJson(acessTokenInfo, HashMap.class);
            String openid = (String) acessTokenMap.get("openid");
            String access_token = (String) acessTokenMap.get("access_token");

            Member member = memberService.getOpenMemer(openid);

            if (member == null) {//如果返回为空，说明该用户没有注册
                //通过微信固定地址，获取扫码人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfoUrl = String.format(baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo=" + userInfo);
                //把扫码人信息存入数据库
                HashMap user = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) user.get("nickname");//昵称
                String headimgurl = (String) user.get("headimgurl");//头像

                member = new Member();
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                member.setNickname(nickname);
                memberService.save(member);
            }

            //解决跨域
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token="+jwtToken;

        } catch (Exception e) {
            throw new GuliException(20001, "登陆失败");
        }
    }
}
